package com.aat.dxfy.dxyStart;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class DxyStartMakeCodeV1 {
	public static String saveDir = "F:/桌面/时间定势";
	public static String packageStr = "com/aat/dxfy";
	public static String entity;
	public static String beanName;
	public static List<String> fileds = new ArrayList<String>();
	public static List<String> types = new ArrayList<String>();
	public static List<String> texts = new ArrayList<String>();

	public static void main(String[] args) {
		try {
			getBaseInfo4Xlsm("cctv_set_timeset.xlsm");

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 0,读取xlsm 形式
	public static void getBaseInfo4Xlsm(String tab) throws IOException {
		InputStream is = new FileInputStream(saveDir + "/"+tab);
		@SuppressWarnings("resource")
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
		
		//读取目录
		XSSFSheet xssfSheetML = xssfWorkbook.getSheetAt(0);
		
		for (int i = 1; i <= xssfSheetML.getLastRowNum(); i++){
			XSSFRow rowML = xssfSheetML.getRow(i);
			if(rowML==null){
				continue;
			}
			String tbName=getXlssVal(rowML.getCell(2));
			String isOk=getXlssVal(rowML.getCell(4));
			
			if(isNotEmpty(tbName)&&isNotEmpty(isOk)){
				if("是".equals(isOk)){
					XSSFSheet xssfSheet = xssfWorkbook.getSheet(tbName);
					//
					if(null!=xssfSheet){
						//装数
						entity = xssfSheet.getSheetName();
						String str = entity.split("_")[1];
						beanName = str.substring(0, 1).toUpperCase()
								+ str.substring(1, str.length());
						fileds.clear();
						types.clear();
						texts.clear();
						//
						for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++){
							XSSFRow xssfRow = xssfSheet.getRow(rowNum);
							String text=getXlssVal(xssfRow.getCell(1));
							String filed=getXlssVal(xssfRow.getCell(2));
							String type=getXlssVal(xssfRow.getCell(3));
							fileds.add(filed);
							types.add(getFiledType(type));
							texts.add(text);
						}
						//开始
						createJavaBean();

						createDao();

						createDaoXml();

						createService();

						createServiceImpl();
						
						createWebController();

						toFormDiv();
						//结束
					}
					//
				}
			}
		}
		
		is.close();
	}
	
	private static String getXlssVal(XSSFCell c){
		if (c.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(c.getBooleanCellValue());
		} else if (c.getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
			return String.valueOf(c.getNumericCellValue());
		}else{
			return String.valueOf(c.getStringCellValue());
		}
	}
	



	// 2,根据读取的信息，创建实体类,{entity}.java
	public static void createJavaBean() {
		String pathname = packageStr + "/" + beanName.toLowerCase() + "/bean";
		createPackage(saveDir + "/" + pathname);
		String[] ss = pathname.split("/");
		String spackage = "";
		for (int i = 0; i < ss.length; i++) {
			spackage += ss[i] + ".";
		}
		spackage = spackage.substring(0, spackage.length() - 1);

		StringBuffer sb = new StringBuffer();
		sb.append("package " + spackage + ";\n\n");
		sb.append("import java.io.Serializable;\n");
		sb.append("import java.util.*;\n\n");

		sb.append("public class " + beanName + "  implements Serializable{\n");

		sb.append("    private static final long serialVersionUID = 1L;\n");
		for (int i = 0; i < fileds.size(); i++) {
			sb.append("    private " + types.get(i) + " " + fileds.get(i)
					+ ";\n");
		}
		sb.append("}\n");
		writeS(new String(sb), "utf-8", saveDir + "/" + pathname + "/"
				+ beanName + ".java");
	}

	// 3-1,根据读取的信息，创建实体Dao,{entity}Dao.java\{entity}Dao.xml
	public static void createDao() {
		String pathname = packageStr + "/" + beanName.toLowerCase() + "/dao";
		createPackage(saveDir + "/" + pathname);
		String[] ss = pathname.split("/");
		String spackage = "";
		for (int i = 0; i < ss.length; i++) {
			spackage += ss[i] + ".";
		}
		spackage = spackage.substring(0, spackage.length() - 1);

		StringBuffer sb = new StringBuffer();
		sb.append("package " + spackage + ";\n\n");
		sb.append("import java.util.*;\n");
		sb.append("import org.springframework.stereotype.Repository;\n");
		sb.append("import " + spackage.replaceAll("dao", "bean.") + beanName
				+ ";\n\n");

		sb.append("@Repository\n");
		sb.append("public interface " + beanName + "Dao{\n\n");

		sb.append("    int addBean(" + beanName + " bean);\n\n");
		sb.append("    int updateBean(" + beanName + " bean);\n\n");
		sb.append("    int deleteBean(String id);\n\n");
		sb.append("    " + beanName + " queryBean(String id);\n\n");
		sb.append("    List<" + beanName
				+ "> queryAll(Map<String, Object> map);\n\n");
		sb.append("    long queryCount(Map<String, Object> map);\n\n");

		sb.append("}\n");
		writeS(new String(sb), "utf-8", saveDir + "/" + pathname + "/"
				+ beanName + "Dao.java");
	}

	// 3-2,根据读取的信息，创建实体Dao,{entity}Dao.java\{entity}Dao.xml
	public static void createDaoXml() {
		String pathname = packageStr + "/" + beanName.toLowerCase() + "/dao";
		createPackage(saveDir + "/" + pathname);
		String[] ss = pathname.split("/");
		String spackage = "";
		for (int i = 0; i < ss.length; i++) {
			spackage += ss[i] + ".";
		}
		spackage = spackage.substring(0, spackage.length() - 1);

		StringBuffer sb = new StringBuffer();
		// head
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
		sb.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\n\"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
		sb.append("<mapper namespace=\"" + spackage + "." + beanName
				+ "Dao\">\n\n");

		// 表
		sb.append("    <!-- 表 -->\n");
		sb.append("    <sql id=\"Table_Name\">\n");
		sb.append("        " + entity + "\n");
		sb.append("    </sql>\n\n");

		// 字段
		sb.append("    <!-- 字段 -->\n");
		sb.append("    <sql id=\"Base_Column_List\">\n");
		String column = "        ";
		for (int i = 0; i < fileds.size(); i++) {
			if (i != 0 && i % 5 == 0) {
				column += "\n        ";
			}
			String f = fileds.get(i);
			if (isNotEmpty(f)) {
				column += f + ",";
			}
		}
		column = column.substring(0, column.length() - 1);
		sb.append(column + "\n");
		sb.append("    </sql>\n\n");
		//

		// add
		sb.append("    <!-- 新增 -->\n");
		sb.append("    <insert id=\"addBean\" parameterType=\"" + beanName
				+ "\">\n");
		sb.append("        INSERT INTO\n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        (\n");
		sb.append("        <include refid=\"Base_Column_List\" />\n");
		sb.append("        ) VALUES\n");
		sb.append("        (\n");
		String columnkh = "        ";
		for (int i = 0; i < fileds.size(); i++) {
			if (i != 0 && i % 5 == 0) {
				columnkh += "\n        ";
			}
			String f = fileds.get(i);
			if (isNotEmpty(f)) {
				columnkh += "#{" + f + "},";
			}
		}
		columnkh = columnkh.substring(0, columnkh.length() - 1);
		sb.append(columnkh + "\n");
		sb.append("        )\n");
		sb.append("    </insert>\n\n");
		//

		// upt
		sb.append("    <!-- 修改 -->\n");
		sb.append("    <update id=\"updateBean\" parameterType=\"" + beanName
				+ "\">\n");
		sb.append("        UPDATE\n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        <set>\n");
		sb.append("            <include refid=\"updateSQL\"/>\n");
		sb.append("        </set>\n");
		sb.append("        WHERE id = #{id}\n");
		sb.append("    </update>\n\n");

		// del
		sb.append("    <!-- 删除 -->\n");
		sb.append("    <delete id=\"deleteBean\" parameterType=\"java.lang.String\">\n");
		sb.append("        DELETE FROM\n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        WHERE id = #{id}\n");
		sb.append("    </delete>\n\n");

		// queryBean
		sb.append("    <!-- 查询单个 -->\n");
		sb.append("    <select id=\"queryBean\" parameterType=\"java.lang.String\" resultType=\""
				+ beanName + "\">\n");
		sb.append("        SELECT <include refid=\"Base_Column_List\" /> FROM \n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        WHERE id = #{id}\n");
		sb.append("    </select>\n\n");

		// queryAll
		sb.append("    <!-- 查询所有 -->\n");
		sb.append("    <select id=\"queryAll\" parameterType=\"java.util.Map\" resultType=\""
				+ beanName + "\">\n");
		sb.append("        SELECT <include refid=\"Base_Column_List\" /> FROM \n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        <include refid=\"condition\" />\n");
		sb.append("        <include refid=\"splitPages\" />\n");
		sb.append("    </select>\n\n");

		// queryCount
		sb.append("    <!-- 查询总数 -->\n");
		sb.append("    <select id=\"queryCount\" parameterType=\"java.util.Map\" resultType=\"java.lang.Long\">\n");
		sb.append("        SELECT COUNT(*) FROM \n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        <include refid=\"condition\" />\n");
		sb.append("    </select>\n\n");

		// uptsql
		sb.append("    <sql id=\"updateSQL\">\n");
		String uptsql = "";
		for (int i = 0; i < fileds.size(); i++) {
			String f = fileds.get(i);
			if (isNotEmpty(f)) {
				uptsql += "        <if test=\"" + f + " != null\">" + f
						+ " = #{" + f + "},</if>\n";
			}
		}
		sb.append(uptsql + "\n");
		sb.append("    </sql>\n\n");

		// con
		sb.append("    <sql id=\"condition\">\n");
		sb.append("        <where>\n");
		String consql = "";
		for (int i = 0; i < fileds.size(); i++) {
			String f = fileds.get(i);
			if (isNotEmpty(f)) {
				consql += "            <if test=\"" + f + " != null\">AND " + f
						+ " = #{" + f + "} </if>\n";
			}
		}
		sb.append(consql + "\n");
		sb.append("      </where>\n");
		sb.append("    </sql>\n\n");

		// split
		sb.append("    <sql id=\"splitPages\">\n");
		sb.append("        <if test=\"sortFiled != null\">\n");
		sb.append("            ORDER BY ${sortFiled}\n");
		sb.append("        </if>\n");
		sb.append("        <if test=\"sortFiled != null and direction != null \">\n");
		sb.append("            ${direction}\n");
		sb.append("        </if>\n");
		sb.append("        <if test=\"start!=null\">\n");
		sb.append("            LIMIT #{start}\n");
		sb.append("        </if>\n");
		sb.append("        <if test=\"start!=null and perpage!=null\">\n");
		sb.append("            ,#{perpage}\n");
		sb.append("        </if>\n");
		sb.append("    </sql>\n\n");
		sb.append("</mapper>\n");
		//
		writeS(new String(sb), "utf-8", saveDir + "/" + pathname + "/"
				+ beanName + "Dao.xml");
	}

	// 4-1,根据读取的信息，创建实体service,{entity}Service.java\{entity}ServiceImpl.java
	public static void createService() {
		String pathname = packageStr + "/" + beanName.toLowerCase()
				+ "/service";
		createPackage(saveDir + "/" + pathname);
		String[] ss = pathname.split("/");
		String spackage = "";
		for (int i = 0; i < ss.length; i++) {
			spackage += ss[i] + ".";
		}
		spackage = spackage.substring(0, spackage.length() - 1);

		StringBuffer sb = new StringBuffer();
		sb.append("package " + spackage + ";\n\n");
		sb.append("import java.util.*;\n");
		sb.append("import " + spackage.replaceAll("service", "bean.")
				+ beanName + ";\n\n");

		sb.append("public interface " + beanName + "Service{\n\n");

		sb.append("    int addBean(" + beanName + " bean);\n\n");
		sb.append("    int updateBean(" + beanName + " bean);\n\n");
		sb.append("    int deleteBean(String id);\n\n");
		sb.append("    " + beanName + " queryBean(String id);\n\n");
		sb.append("    List<" + beanName
				+ "> queryAll(Map<String, Object> map);\n\n");
		sb.append("    long queryCount(Map<String, Object> map);\n\n");

		sb.append("}\n");
		writeS(new String(sb), "utf-8", saveDir + "/" + pathname + "/"
				+ beanName + "Service.java");
	}

	// 4-2,根据读取的信息，创建实体service,{entity}Service.java\{entity}ServiceImpl.java
	public static void createServiceImpl() {
		String pathname = packageStr + "/" + beanName.toLowerCase()
				+ "/service";
		createPackage(saveDir + "/" + pathname + "/impl");
		String[] ss = pathname.split("/");
		String spackage = "";
		for (int i = 0; i < ss.length; i++) {
			spackage += ss[i] + ".";
		}
		spackage = spackage.substring(0, spackage.length() - 1);

		StringBuffer sb = new StringBuffer();
		sb.append("package " + spackage + ".impl;\n\n");
		sb.append("import java.util.*;\n\n");

		sb.append("import org.springframework.beans.factory.annotation.Autowired;\n");
		sb.append("import org.springframework.stereotype.Service;\n\n");

		sb.append("import " + spackage.replaceAll("service", "bean.")
				+ beanName + ";\n");
		sb.append("import " + spackage.replaceAll("service", "dao.") + beanName
				+ "Dao;\n");
		sb.append("import " + spackage + "." + beanName + "Service;\n\n");

		sb.append("@Service\n");
		sb.append("public class " + beanName + "ServiceImpl  implements "
				+ beanName + "Service {\n\n");

		String dao = beanName.toLowerCase() + "Dao";
		sb.append("    @Autowired\n");
		sb.append("    private " + beanName + "Dao " + dao + ";\n\n");

		sb.append("    public int addBean(" + beanName + " bean){\n");
		sb.append("        return " + dao + ".addBean(bean);\n");
		sb.append("    }\n\n");

		sb.append("    public int updateBean(" + beanName + " bean){\n");
		sb.append("        return " + dao + ".updateBean(bean);\n");
		sb.append("    }\n\n");

		sb.append("    public int deleteBean(String id){\n");
		sb.append("        return " + dao + ".deleteBean(id);\n");
		sb.append("    }\n\n");

		sb.append("    public " + beanName + " queryBean(String id){\n");
		sb.append("        return " + dao + ".queryBean(id);\n");
		sb.append("    }\n\n");

		sb.append("    public List<" + beanName
				+ "> queryAll(Map<String, Object> map){\n");
		sb.append("        return " + dao + ".queryAll(map);\n");
		sb.append("    }\n\n");

		sb.append("    public long queryCount(Map<String, Object> map){\n");
		sb.append("        return " + dao + ".queryCount(map);\n");
		sb.append("    }\n\n");

		sb.append("}\n");
		writeS(new String(sb), "utf-8", saveDir + "/" + pathname
				+ "/impl/" + beanName + "ServiceImpl.java");
	}

	// 5,根据读取的信息，创建实体controller,{entity}Controller.java
	// add,edit,upt,del,view,list,listJson
	public static void createWebController(){
		String pathname = packageStr + "/" + beanName.toLowerCase()
				+ "/web";
		createPackage(saveDir + "/" + pathname + "/controller");
		String[] ss = pathname.split("/");
		String spackage = "";
		for (int i = 0; i < ss.length; i++) {
			spackage += ss[i] + ".";
		}
		spackage = spackage.substring(0, spackage.length() - 1);

		StringBuffer sb = new StringBuffer();
		sb.append("package " + spackage + ".controller;\n\n");

		sb.append("import org.springframework.context.annotation.Scope;\n");
		sb.append("import org.springframework.web.bind.annotation.*;\n");
		sb.append("import org.springframework.stereotype.Controller;\n\n");
		
		sb.append("import com.aat.dxfy.base.web.controller.BaseController;\n\n");
		
		
		sb.append("@Controller\n@Scope(\"prototype\")\n@RequestMapping(\" \")\n");
		sb.append("public class Master" + beanName + "Controller  extends BaseController{\n\n");


		sb.append("}\n");
		writeS(new String(sb), "utf-8", saveDir + "/" + pathname
				+ "/controller/Master" + beanName + "Controller.java");
	}

	// 6,创建html文件的DIV-Form表单文件
 	public static void toFormDiv() {
		String str = "";
		int i = 0;
		for (String s : fileds) {
			if (null != s) {
				str = str + "<div class=\"form-group \">\n";
				str = str + "    <label for=\"" + s
						+ "\" class=\"control-label col-lg-2\">" + texts.get(i)
						+ "</label>\n";
				str = str + "    <div class=\"col-lg-6\">\n";
				str = str + "        <input class=\" form-control\" id=\"" + s
						+ "\" name=\"" + s + "\"  value=\"${m." + s
						+ "}\"  type=\"text\" required />\n";
				str = str + "    </div>\n</div>\n";
				i++;
			}
		}
		str += "\n\n\n";
		writeS(str, "utf-8", saveDir + "/div" + beanName + ".html");
	}

	// 101:根据字段类型，得到java的属性类型；
	public static String getFiledType(String str) {
		if (str.toLowerCase().contains("char")) {
			return "String";
		}
		if (str.toLowerCase().startsWith("int")) {
			return "Integer";
		}
		if (str.toLowerCase().contains("bigint")) {
			return "Long";
		}
		if (str.toLowerCase().contains("float")
				|| str.toLowerCase().contains("double")
				|| str.toLowerCase().contains("num")
				|| str.toLowerCase().contains("dec")) {
			return "Double";
		}
		if (str.toLowerCase().contains("date")) {
			return "Date";
		}
		return "String";
	}

	// 102:创建文件包
	public static void createPackage(String pathname) {
		File f = new File(pathname);
		if (!f.exists()) {
			f.mkdirs();
		}
	}
	
	//103
	private static boolean isNotEmpty(String str){
		if(null==str){
			return false;
		}
		if("".equals(str)||str.length()==0){
			return false;
		}
		return true;
		
	}
	
	//104
	private static void writeS(String str, String encoding, String file) {
		char[] cuf = str.toCharArray();// 将指定的字串序列化为byte[]
		try {
			OutputStreamWriter out = new OutputStreamWriter(
					new FileOutputStream(file), encoding);
			out.write(cuf);
			out.flush();
			out.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
